#!/bin/sh

find_self() {
	SELF_DIR=`dirname $0`
}

shmount() {
	$MOUNT -t $MOUNTTYPE -o rw $SHARED $MOUNTPOINT
}

shumount() {
	$UMOUNT $SHARED
}

create_env() {
	mkdir -p $MOUNTPOINT/playpen
	mkdir -p $MOUNTPOINT/storage
	
	PLAYPEN="/tmp/vmexec-$$/playpen"
	STORAGE="/tmp/vmexec-$$/storage"
	export PLAYPEN STORAGE
		
	mkdir -p $PLAYPEN
	mkdir -p $STORAGE

	cp -r $MOUNTPOINT/playpen/* $PLAYPEN
	cp -r $MOUNTPOINT/storage/* $STORAGE
	
	cd $PLAYPEN
}

run_application() {
	dos2unix $APP_SCRIPT
	$SH $APP_SCRIPT > $APP_STDOUT 2> $APP_STDERR
	echo $? > $APP_EXIT
}

cleanup() {
	cd $CURRENT_DIR
	rm -rf $PLAYPEN
	rm -rf $STORAGE
}

copy_results() {
	mkdir -p $MOUNTPOINT/playpen
	mkdir -p $MOUNTPOINT/storage
	cp -r $PLAYPEN/* $MOUNTPOINT/playpen
	cp -r $STORAGE/* $MOUNTPOINT/storage
}

#MAIN
find_self
. $SELF_DIR/VBOX_OPTS

CURRENT_DIR=`pwd`

echo "Cleaning Evironment"
cleanup

echo "Mounting Shared Folder"
shmount

echo "Copying Files"
create_env

echo "Unmounting Shared Folder"
shumount

echo "Executing Applications"
run_application

echo "Copying Results"
shmount
copy_results

echo "Cleaning up"
cleanup

touch $MOUNTPOINT/playpen/$TERMINATION_FILE
